package com.ruiya.staging.goods.locate.grpc;


import com.ruiya.staging.goods.data.grpc.DataURI;
import com.ruiya.staging.goods.data.grpc.LocateGoodsIdRequest;
import com.ruiya.staging.goods.data.grpc.LocateGoodsIdResponse;
import com.ruiya.staging.goods.locate.client.DataIOClient;
import com.ruiya.staging.goods.locate.util.GrpcResponseUtils;
import com.ruiya.staging.goods.locate.util.LocateRpcStatus;
import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.server.service.GrpcService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.MessageFormat;

@GrpcService
public class LocateGrpcService extends LocateIOServiceGrpc.LocateIOServiceImplBase {
    private static final Logger _log = LoggerFactory.getLogger(LocateGrpcService.class);

    @Autowired
    DataIOClient dataIOClient;

    @Override
    public void getGoodsId(GetGoodsIdRequest request, StreamObserver<GetGoodsIdResponse> responseObserver) {
        String tid = "";
        try{
            tid = request.getTid();
            String entId = request.getEntId();
            String goodsNo = request.getGoodsNo();
            LocateGoodsIdRequest grpcRequest = LocateGoodsIdRequest.newBuilder()
                    .setUri(DataURI.newBuilder().setTid(tid).setSharding("none").build())
                    .setEntId(entId)
                    .setGoodsNo(goodsNo)
                    .build();

            LocateGoodsIdResponse grpcResponse = this.dataIOClient.locateGoodsId(grpcRequest);
            if(grpcResponse.getStatus().getCode() != com.ruiya.staging.goods.data.grpc.RpcStatus.Codes.OK_VALUE){
                GrpcResponseUtils.doGetGoodsIdError(responseObserver, RpcStatus.Codes.InvokeFail_VALUE, grpcResponse.getStatus().getMemo());
                return;
            }

            GetGoodsIdResponse response = GetGoodsIdResponse.newBuilder()
                    .setStatus(LocateRpcStatus.ok())
                    .setGoodsId(grpcResponse.getGoodsId())
                    .build();
            responseObserver.onNext(response);
            responseObserver.onCompleted();

        }catch (Exception ex) {
            _log.error(MessageFormat.format("getGoodsId, tid={0}", tid), ex);
            GrpcResponseUtils.doGetGoodsIdError(responseObserver, RpcStatus.Codes.Exception_VALUE, ex.getMessage());
        }
    }
}
